import React, { useEffect, useState } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  message,
  Tabs,
  DatePicker
} from 'antd';
import {
  UserOutlined,
  BookOutlined,
  TeamOutlined,
  RiseOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchDashboardData, updateAnnouncement } from '../../store/adminSlice';

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

const Dashboard = () => {
  const dispatch = useDispatch();
  const [timeRange, setTimeRange] = useState('week'); // week, month, year
  const [isAnnouncementModalVisible, setIsAnnouncementModalVisible] = useState(false);
  const [form] = Form.useForm();

  const adminState = useSelector(state => state.admin) || {};
  const {
    statistics = {
      totalUsers: 0,
      newUsers: 0,
      totalCourses: 0,
      activeUsers: 0,
      activeRate: 0,
      totalRevenue: 0,
      revenueGrowth: 0
    },
    courseData = {
      salesTrend: [],
      courses: []
    },
    userData = {
      activityData: [],
      retentionRate: 0
    },
    announcements = [],
    loading = false
  } = adminState;

  // 定期刷新数据
  useEffect(() => {
    const fetchData = () => {
      dispatch(fetchDashboardData(timeRange));
    };

    fetchData();
    const timer = setInterval(fetchData, 60000); // 每分钟刷新一次

    return () => clearInterval(timer);
  }, [dispatch, timeRange]);

  // 课程销量趋势图配置
  const courseSalesOption = {
    title: {
      text: '课程销量趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: courseData?.salesTrend?.map(item => item.date) || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '销量',
        type: 'line',
        data: courseData?.salesTrend?.map(item => item.sales) || [],
        smooth: true
      }
    ]
  };

  // 用户活跃度图表配置
  const userActivityOption = {
    title: {
      text: '用户活跃度分析'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: userData?.activityData?.map(item => item.date) || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '日活跃用户',
        type: 'bar',
        data: userData?.activityData?.map(item => item.activeUsers) || []
      }
    ]
  };

  // 用户留存率图表配置
  const userRetentionOption = {
    title: {
      text: '用户留存率'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '留存率',
        type: 'pie',
        radius: ['50%', '70%'],
        data: [
          { value: userData?.retentionRate || 0, name: '留存用户' },
          { value: 100 - (userData?.retentionRate || 0), name: '流失用户' }
        ]
      }
    ]
  };

  // 课程分类数据表格列配置
  const courseColumns = [
    {
      title: '课程名称',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '学员数量',
      dataIndex: 'studentCount',
      key: 'studentCount',
      sorter: (a, b) => a.studentCount - b.studentCount
    },
    {
      title: '完成率',
      dataIndex: 'completionRate',
      key: 'completionRate',
      render: (text) => `${text}%`,
      sorter: (a, b) => a.completionRate - b.completionRate
    },
    {
      title: '平均评分',
      dataIndex: 'rating',
      key: 'rating',
      render: (text) => `${text}分`,
      sorter: (a, b) => a.rating - b.rating
    }
  ];

  // 发布公告
  const handleAnnouncementSubmit = (values) => {
    dispatch(updateAnnouncement({
      id: Date.now(),
      ...values,
      createTime: new Date().toISOString()
    }));
    setIsAnnouncementModalVisible(false);
    form.resetFields();
    message.success('公告发布成功！');
  };

  return (
    <div style={{ padding: 24 }}>
      {/* 顶部统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={statistics.totalUsers}
              prefix={<UserOutlined />}
              suffix={
                <span style={{ fontSize: 14, color: '#52c41a' }}>
                  +{statistics.newUsers} 今日新增
                </span>
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总课程数"
              value={statistics.totalCourses}
              prefix={<BookOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={statistics.activeUsers}
              prefix={<TeamOutlined />}
              suffix={
                <span style={{ fontSize: 14, color: '#1890ff' }}>
                  {statistics.activeRate}%
                </span>
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总收入"
              value={statistics.totalRevenue}
              prefix="¥"
              suffix={
                <span style={{ fontSize: 14, color: '#52c41a' }}>
                  <RiseOutlined /> {statistics.revenueGrowth}%
                </span>
              }
            />
          </Card>
        </Col>
      </Row>

      {/* 时间范围选择 */}
      <Space style={{ marginBottom: 24 }}>
        <RangePicker onChange={(dates) => {
          // 处理日期范围变化
        }} />
        <Button
          icon={<ReloadOutlined />}
          onClick={() => dispatch(fetchDashboardData(timeRange))}
        >
          刷新数据
        </Button>
        <Button
          type="primary"
          onClick={() => setIsAnnouncementModalVisible(true)}
        >
          发布公告
        </Button>
      </Space>

      {/* 图表展示区域 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card>
            <ReactECharts option={courseSalesOption} />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <ReactECharts option={userActivityOption} />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card>
            <ReactECharts option={userRetentionOption} />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="课程数据">
            <Table
              columns={courseColumns}
              dataSource={courseData?.courses}
              rowKey="id"
              pagination={{ pageSize: 5 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 公告发布对话框 */}
      <Modal
        title="发布公告"
        visible={isAnnouncementModalVisible}
        onCancel={() => setIsAnnouncementModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          onFinish={handleAnnouncementSubmit}
          layout="vertical"
        >
          <Form.Item
            name="title"
            label="公告标题"
            rules={[{ required: true, message: '请输入公告标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="content"
            label="公告内容"
            rules={[{ required: true, message: '请输入公告内容' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              发布
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Dashboard; 